<?php

/**
 * @copyright: ©2024 永州微聚 商网络科技有限公司
 * @link: https://www.weijuYunke.com
 */
namespace app\mobile\controller;

use AlibabaCloud\Config\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\admin\model\Banner;
use app\admin\model\HelpTutoria;
use app\admin\model\MessageConfig;
use app\admin\model\Platform;
use app\admin\model\PlatformUpload;
use app\admin\model\SmsMessage;
use app\admin\model\Template;
use app\BaseController;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\App;
use think\Exception;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Filesystem;
use think\Model;
use app\admin\model\FigureSystem;
use app\admin\model\FigurePayLog;
use app\admin\model\FigureNavigation;
use app\admin\model\FigureBanner;
use app\admin\model\FigureService;
use app\admin\model\FigureCard;
use app\admin\model\FigureCardGoods;
use app\admin\model\FigureCardLog;
use app\admin\model\FigureMemberLog;
use app\admin\model\FigureUser;
use app\common\service\ApiService;
use think\file\UploadedFile;
use FFMpeg\FFMpeg;
use app\common\service\Sms;
use app\admin\model\FigureIndexSet;
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true'); // 是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); // 允许的请求类型
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
// 允许的请求头字段

/**
 * 首页
 *
 * @author Administrator
 *        
 */
class Index extends BaseController
{





    /**
     * 阿里云配置
     * http://aigc.weijuyunke.cn/mobile/index/aliyunConfig
     */
    public function aliyunConfig()
    {
        return result(0, 'success', [
            'alioss_access_key_id' => sysconfig('upload', 'alioss_access_key_id'),
            'alioss_access_key_secret' => sysconfig('upload', 'alioss_access_key_secret'),
            'alioss_endpoint' => sysconfig('upload', 'alioss_endpoint'),
            'alioss_bucket' => sysconfig('upload', 'alioss_bucket'),
            'alioss_domain' => sysconfig('upload', 'alioss_domain')
        ]);
    }



    /**
     * 支付设置
     * http://aigc.weijuyunke.cn/mobile/index/payconfig
     */
    public function payconfig()
    {
        return result(0, 'success', [
            'pay_open' => sysconfig('pay', 'pay_open')
        ]);
    }





    /**
     * 系统设置
     * http://aigc.weijuyunke.cn/mobile/index/system
     */
    public function system()
    {
        $request = $this->request;
        $where[] = ['id','=', $request->platform_id];
        $platfrom = new Platform();
        $platfromInfo =  $platfrom ->where($where)->find();
        $siteSet = sysconfig('site');
        $platfromInfo['appid'] = $siteSet['appid'];
        $platfromInfo['appsecret'] = $siteSet['appsecret'];
        $platfromInfo['review_switch'] = $siteSet['review_switch'];

        return result(0,'上传成功', $platfromInfo);
    }


    /**
     * 上传图片
     * http://aigc.weijuyunke.cn/mobile/index/upload
     *
     * @param
     *            file
     */
    public function upload()
    {
        $request = $this->request;
        $siteSet = sysconfig('upload');
        $where[] = ['platform_id','=', $request->platform_id];
        $platformModel = new PlatformUpload();
        $siteSet =  $platformModel->where($where)->find();

        $files = $request->file("file");
        if (!$files){
            return result(-1,'请上传文件');
        }
        $ext = $files->extension();
        if ( empty($siteSet) || $siteSet['upload_type'] == 'local') {
            try {
                $path = 'uploads';
                // 将图片保存至本地
                $saveName = \think\facade\Filesystem::disk('public')->putFile($path, $files);
                $saveName = $request->domain() .'/'. $saveName;
                return result(0,'上传成功',  $saveName);
                //将文件上传的路径返回
            } catch (\think\exception\ValidateException $e) {
                return result(-1,$e->getMessage());
            }
        } else if ($siteSet['qnoss'] == 'qnoss') {
            if ($siteSet['upload_allow_ext']){
                $fileTypeArray = explode(',',$siteSet['upload_allow_ext']);
                if (!in_array($ext,$fileTypeArray)){
                    return result(-1,'此类型文件不允许上传');
                }
            }
            $qiniu_access_key = $siteSet['qnoss_access_key'];
            $qiuniu_secret = $siteSet['qnoss_secret_key'];
            $qiniu_bucket = $siteSet['qnoss_bucket'];
            // 构建Auth对象
            $auth = new Auth($qiniu_access_key, $qiuniu_secret);
            // 要上传的空间
            $bucket = $qiniu_bucket;
            // 生成上传Token
            $token = $auth->uploadToken($bucket);
            // 上传到七牛后的文件名
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();
            // 初始化UploadManager类
            $uploadMgr = new UploadManager();
            list($ret, $err) = $uploadMgr->putFile($token, $key, $files->getRealPath());
            if ($err !== null) {
                return false;
            } else {
                $url = $siteSet['qnoss_domain'] . '/'.$ret['key'];
                return result(0,'上传成功', $url);
            }
        }else{
            if ($siteSet['upload_allow_ext']){
                $fileTypeArray = explode(',',$siteSet['upload_allow_ext']);
                if (!in_array($ext,$fileTypeArray)){
                    return result(-1,'此类型文件不允许上传');
                }
            }
            $accessKeyId = $siteSet['alioss_access_key_id'];
            $accessKeySecret = $siteSet['alioss_access_key_secret'];
            $endpoint = $siteSet['alioss_endpoint'];
            $bucket = $siteSet['alioss_bucket'];
            //实例化对象 将配置传入
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $key = date('Y-m-d') . '/' . substr(md5($files->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $files->extension();
            $result = $ossClient->uploadFile($bucket, $key, $files->getRealPath());
            $url = $result['info']['url'];
            $arr = parse_url($url);
            if($arr['scheme'] == 'http'){
                $url = 'https://' . $arr['host'] . $arr['path'];
            }
            //将结果输出
            return result(0,'上传成功',$url);
        }
    }
    public function  banner(){
        $request = $this->request;
        $where[] = ['platform_id','=', $request->platform_id];
        $where[] = ['is_display','=', 1];
        $Banner= new Banner();
        $platfromInfo =  $Banner ->where($where)->select();
        return result(0,'上传成功', $platfromInfo);
    }

    public function sendMessage()
    {

        $request = $this->request;
        $param = $request->param();
        $chars = '0123456789';
        $str = '';
        for ($i = 0; $i < 4; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $where[] = ['platform_id','=', $request->platform_id];
        $MessageConfig= new MessageConfig();
        $platfromInfo =  $MessageConfig ->where($where)->find();
//        var_dump($platfrom->getLastSql());exit;
      /*  $accessKeyId = Config::getConfigValue('ali_duanxin_access_key_id');//为企阿里云账号秘钥ID
        $accessKeySecret = Config::getConfigValue('ali_duanxin_access_key_secret');;//秘钥*/

        $config = new \Darabonba\OpenApi\Models\Config(['accessKeyId' => $platfromInfo['alimessage_access_key_id'], 'accessKeySecret' => $platfromInfo['alimessage_access_key_secret']]);
        /*  var_dump($config);exit;*/


        $config->endpoint ="dysmsapi.aliyuncs.com";

        $client = new \AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi($config);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $param['phone'],
            "signName" => $platfromInfo['alimessage_template_name'],    //    签名
            "templateCode" => $platfromInfo['alimessage_tid'],    //    模板
            "templateParam" => json_encode(['code' => $str])
        ]);
        $runtime = new RuntimeOptions([]);
        $res = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        if ($res->body->code == 'OK') {
            $smsMessageModel = new SmsMessage();
            $smsMessageModel->save(['telphone' => $param['phone'], 'create_time' => time(), 'code' => $str, 'effective_time' => time() + 300]);
            return result(0,'发送成功', ['code' => $str]);
        } else {
            return result(-1,'发送失败', ['code' => $str]);
        }
    }

    public function template(){
        $request = $this->request;
        $param = $request->param();
        $template = new Template();
        $where[] = ['platform_id','=', $request->platform_id];
        $templateList = $template->where($where)->select()->toArray();
        $data= [];
        if ($templateList){
            $data =array_column($templateList,'template_id','name');
        }
        return result(0,'通知模板', $data);
    }

    /**
     * 获取openid
     * mobile/user/getOpenId
     *
     * @param
     *            code
     */
    public function getOpenId()
    {

        $request = $this->request;
        $siteSet = sysconfig('site');
        $param = $request->param();
        $code = input('code');
        if (empty($code)) {
            return result(-1, 'code为空');
        }
        $appid = $siteSet['appid'];
        $secret = $siteSet['appsecret'];
        $api = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $appid . "&secret=" . $secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $info = httpGet($api); // get请求网址，获取数据
        $json = json_decode($info); // 对json数据解码
        $arr = get_object_vars($json); // 返回一个数组。获取$json对象中的属性，组成一个数组
        if (!empty($arr['errcode'])) {
            return result(-1, $arr['errmsg']);
        } else {
            $openid = $arr['openid'];
            if (empty($openid)) {
                return result(-1, 'fail');
            } else {
                if (isset($arr['unionid']) &&$arr['unionid']  ) {
                    $data['gather_unionid'] = $arr['unionid'];
                }
                if (isset($arr['openid']) && $arr['openid']  ) {
                    $data['gather_openid'] = $arr['openid'];
                }
                $userModel = new \app\admin\model\User;
                $userModel->where(['id' => $param['id']])->update($data);
                return result(0, 'success');
            }
        }
    }

    /**
     * 获取微信授权手机号码
     * mobile/user/getTelphone
     *
     * @param
     *            code
     */
//    public function getTelphone()
//    {
//
//        $request = $this->request;
//
//        $siteSet = sysconfig('site');
//
//        $code = input('code');
//        if (empty($code)) {
//            return result(-1, 'code为空');
//        }
//        $appid = $siteSet['appid'];
//        $secret = $siteSet['appsecret'];
//
//        $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
//
//        $info = httpGet($api); // get请求网址，获取数据
//        $arr_access_token = json_decode($info, true); // 对json数据解码
//
//        if (!$arr_access_token) {
//            return result(-1, '请求异常');
//        }
//
//        $access_token = $arr_access_token['access_token'];
//        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" . $access_token;
//        $send_data = array(
//            'code' => $code
//        );
//        $data = json_encode($send_data);
//        $phone = json_decode(wtw_request($url, $data));
//
//        return result(0, 'success', $phone);
//    }





    public  function gatherSystem()
    {
        $siteSet = sysconfig('site');
        return result(0, 'success', $siteSet);
    }












}